package controladores;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.FConexao;
import util.FData;
import util.FTabelaTemporaria;
import util.Fxml;
import util.NivelAcesso;
import datamodule.ArqlogDAO;
import datamodule.ArqlogVO;
import datamodule.DBuserVO;
import datamodule.TbTemp26DAO;
import datamodule.TbTemp26VO;
import datamodule.UsuarioVO;

/**
 * Servlet implementation class for Servlet: CONFR006
 * 
 */
public class CONFR006 extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public CONFR006() {
		super();
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		String usucodusu = (String) request.getSession().getAttribute("usucodusu");
		String codemp     = (String) request.getSession().getAttribute("codemp");
		////UPDATE DA CONEXAO////////////
		request = FConexao.updateConexao(request); DBuserVO userVO = new DBuserVO(request);
		/////-------------------//////////////
		String tela = "CONFR006";

		
		String Button = request.getParameter("Button");
		
		
		if (codemp == null){
			codemp = "";
		}
		

		if (usucodusu == null){
			usucodusu = "";
		}

		
//		String codusu2 = request.getParameter("codusu2");
//		String codusu3 = request.getParameter("codusu3");
//		String codusu4 = request.getParameter("codusu4");
//		String codusu5 = request.getParameter("codusu5");
//		String codusu6 = request.getParameter("codusu6");
//		String codusu7 = request.getParameter("codusu7");
//		String codusu8 = request.getParameter("codusu8");
		
		String select = request.getParameter("select");
		if(select==null) select = "";
		
		String linhaid = request.getParameter("linhaid");
		if(linhaid==null) linhaid = "";
		
		String usu_codusu = request.getParameter("usu_codusu");
		if(usu_codusu==null) usu_codusu = "";
		
		int exec = 0;

		if (Button == null){
			Button = "Novo";
		}

		String ultimo = FTabelaTemporaria.ultimoNumIp(userVO);
		
		String TbTemp26 = "tb"+usucodusu+ultimo+"75";
		
		TbTemp26DAO DAOt26 = new TbTemp26DAO(userVO);
		ArqlogDAO DAOarq = new ArqlogDAO(userVO);
		
		if(Button.trim().equals("Novo")){			   
			exec = exec + 1;
			RequestDispatcher dispatcher = request.getRequestDispatcher("confr006.jsp");
			dispatcher.forward(request,response);
		}		

		if(Button.trim().equals("Iniciar")){
			exec = exec + 1;		

			StringBuffer retornoxml = new StringBuffer(Fxml.incxml());			
			try{
				///Verificando Nivel de Acesso///
				retornoxml.append(NivelAcesso.testaAcesso(codemp, usucodusu, tela, userVO));
				
				DAOt26.criar_tabela(TbTemp26);
				
				if(retornoxml.indexOf(">T</")>-1){
					retornoxml.append(Fxml.campxml("javascript", "start();//.envia"));
				}
							
			}catch (Exception e) {
				// TODO: handle exception
				retornoxml.append(Fxml.campxml("msme", "Erro "+e.toString()));
			}
			retornoxml.append(Fxml.finxml());	
			response.setContentType("text/xml;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");	
			response.getWriter().write(retornoxml.toString());			
		}
		
		
		if(Button.trim().equals("Atualizar")){
			exec= exec+1;
			//String retorno = "";
			StringBuffer retornoxml = new StringBuffer(Fxml.incxml());
			int marcados;
			try{
				marcados = DAOt26.qteMarcados(TbTemp26);
				ArrayList<UsuarioVO> list = DAOarq.geralUsu(FData.dataHoje(),null);
				if(list!=null){
					for (Iterator<UsuarioVO> iterator = list.iterator(); iterator.hasNext();) {
						UsuarioVO VO = iterator.next();
						
						TbTemp26VO vo26 = DAOt26.pesquisa(TbTemp26, VO.getUsu_codusu());
						if(vo26==null){
							
							String marc = "0";
							if(marcados<6){
								//marc = "1";
								//marcados++;
								//Alterado Leo - se carregasse no inicio, fica muito lento.
								//retornoxml.append(Fxml.campxml("javascript", "criaPanel('"+VO.getUsu_codusu()+"','"+VO.getUsu_operad()+"');"));
								
							}
							
							int i = DAOt26.inserir(TbTemp26, VO.getUsu_codusu(), marc, "0", "0");
							if(i>0){
								retornoxml.append(Fxml.gridinclinxml("grid1"));
								retornoxml.append(Fxml.gridcelxml(String.valueOf(VO.getSql_rowid())));
								retornoxml.append(Fxml.gridcelxml(VO.getUsu_codusu()));
								retornoxml.append(Fxml.gridcelxml(VO.getUsu_operad()));
								retornoxml.append(Fxml.gridcelxml(marc));
								retornoxml.append(Fxml.gridfinlinxml());
						    }
						}
					}
				}
				
				ArrayList<TbTemp26VO> list26 = DAOt26.geral(TbTemp26);
				if(list26!=null){
					for (Iterator<TbTemp26VO> iterator = list26.iterator(); iterator.hasNext();) {
						TbTemp26VO vo26 = iterator.next();
					
						if(vo26.getT260_chave1().equals("1")){
						
							ArrayList<ArqlogVO> listlog = DAOarq.geral(FData.mes2Dig(FData.dataHojeBR()), vo26.getT260_nomtab(), FData.dataHojeBR(), FData.dataHoje(), null,vo26.getT260_chave2());
							if(listlog!=null){
								int i = 0;
								int color = Integer.parseInt(vo26.getT260_chave3());
								for (Iterator<ArqlogVO> iter = listlog.iterator(); iter.hasNext();) {
									ArqlogVO vo = iter.next();
									
									String fcolor ="";
									if(vo.getAql_acaoql().trim().equalsIgnoreCase("EXCLUIR")){
										fcolor = "#FF0000";
									}else if (vo.getAql_acaoql().trim().equalsIgnoreCase("GRAVAR")){
										fcolor = "#0000FF";
									}else if (vo.getAql_acaoql().trim().equalsIgnoreCase("SAIR")){
										fcolor = "#9900FF";
									}else if (vo.getAql_acaoql().trim().equalsIgnoreCase("ENTRAR")){
										if(vo.getAql_progra().trim().equalsIgnoreCase("LOGIN"))fcolor = "#007700";
									}else{
										fcolor = "#000000";
									}
									
									retornoxml.append(Fxml.campxml("div-app-usuario"+(vo26.getT260_nomtab()), 
											"<div title=\"Emp="+vo.getEmp_codemp()+",Descri="+vo.getAql_descri()+",Resposta="+vo.getAql_respos()+"\" " +
													"style=\"cursor:default; font-size: 12px; width:100%; background-color:"+(color==0?"#FFFFFF":"#EEEEEE")+"; color:"+fcolor+";\" " +
															"ondblclick=\"info('"+vo.getEmp_codemp()+"','"+vo.getAql_progra()+"','"+vo.getMod_descri()+"','"+vo.getUsu_codusu()+"','"+vo.getUsu_operad()+"','"+vo.getAql_descri()+"','"+vo.getAql_respos().replaceAll("\\n", "")+"','"+vo.getAql_datsis()+"','"+vo.getAql_dattra()+"','"+vo.getAql_horaql()+"','"+vo.getAql_acaoql()+"');\">" +
															""+vo.getAql_horaql()+" - "+vo.getAql_progra()+" - "+vo.getAql_acaoql()+"" +
																	"</div>"));
									
									color = color==0?1:0;
									if(!iter.hasNext()){
										DAOt26.alterar(TbTemp26, vo26.getT260_nomtab(), null, String.valueOf(vo.getSql_rowid()), String.valueOf(color), vo26.getSql_rowid());
									}
									i++;
								}
								retornoxml.append(Fxml.campxml("javascript", 
										"pega('usuario"+vo26.getT260_nomtab()+"').scrollTop = pega('usuario"+vo26.getT260_nomtab()+"').scrollHeight;"));
							}
						}
						
					}
				
				}
				
			}catch (Exception e) {
				e.printStackTrace();
				retornoxml.append(Fxml.campxml("msme", "Erro: "+e.toString()));
			}
			
			
			retornoxml.append(Fxml.finxml());
			response.setContentType("text/xml;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");	
			response.getWriter().write(retornoxml.toString());

		}
		
		if(Button.trim().equals("AtualizarUsu")){
			exec= exec+1;
			//String retorno = "";
			StringBuffer retornoxml = new StringBuffer(Fxml.incxml());
			try{
				String lastrow = DAOt26.lastRowId(TbTemp26, usu_codusu);
				
				ArrayList<ArqlogVO> listlog = DAOarq.geral(FData.mes2Dig(FData.dataHojeBR()), usu_codusu, FData.dataHojeBR(), FData.dataHoje(), null,lastrow);
				if(listlog!=null){
					int i = 0;
					int color = 0;
					for (Iterator<ArqlogVO> iter = listlog.iterator(); iter.hasNext();) {
						ArqlogVO vo = iter.next();
						
						String fcolor ="";
						if(vo.getAql_acaoql().trim().equalsIgnoreCase("EXCLUIR")){
							fcolor = "#FF0000";
						}else if (vo.getAql_acaoql().trim().equalsIgnoreCase("GRAVAR")){
							fcolor = "#0000FF";
						}else if (vo.getAql_acaoql().trim().equalsIgnoreCase("SAIR")){
							fcolor = "#9900FF";
						}else if (vo.getAql_acaoql().trim().equalsIgnoreCase("ENTRAR")){
							if(vo.getAql_progra().trim().equalsIgnoreCase("LOGIN"))fcolor = "#007700";
						}else{
							fcolor = "#000000";
						}
						
						retornoxml.append(Fxml.campxml("div-app-usuario"+usu_codusu, 
								"<div title=\"Emp="+vo.getEmp_codemp()+",Descri="+vo.getAql_descri()+",Resposta="+vo.getAql_respos()+"\" " +
										"style=\"cursor:default; font-size: 12px; width:100%; background-color:"+(color==0?"#FFFFFF":"#EEEEEE")+"; color:"+fcolor+";\" " +
												"ondblclick=\"info('"+vo.getEmp_codemp()+"','"+vo.getAql_progra()+"','"+vo.getMod_descri()+"','"+vo.getUsu_codusu()+"','"+vo.getUsu_operad()+"','"+vo.getAql_descri()+"','"+vo.getAql_respos()+"','"+vo.getAql_datsis()+"','"+vo.getAql_dattra()+"','"+vo.getAql_horaql()+"','"+vo.getAql_acaoql()+"');\">" +
												""+vo.getAql_horaql()+" - "+vo.getAql_progra()+" - "+vo.getAql_acaoql()+"" +
														"</div>"));
						
						color = color==0?1:0;
						if(!iter.hasNext()){
							DAOt26.alterar(TbTemp26, usu_codusu, null, String.valueOf(vo.getSql_rowid()), String.valueOf(color), 0);
						}
						i++;
					}
					
					retornoxml.append(Fxml.campxml("javascript", 
							"pega('usuario"+usu_codusu+"').scrollTop = pega('usuario"+usu_codusu+"').scrollHeight;"));
				}
			
			}catch (Exception e) {
				e.printStackTrace();
				retornoxml.append(Fxml.campxml("msme", "Erro: "+e.toString()));
			}
			
			
			retornoxml.append(Fxml.finxml());
			response.setContentType("text/xml;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");	
			response.getWriter().write(retornoxml.toString());

		}
		
		if(Button.trim().equals("MarcaL")){
			exec= exec+1;
			//String retorno = "";
			StringBuffer retornoxml = new StringBuffer(Fxml.incxml());
			try{
				
				DAOt26.alterar(TbTemp26, usu_codusu, "1", null, null, Integer.parseInt(linhaid));
				
			}catch (Exception e) {
				e.printStackTrace();
				retornoxml.append(Fxml.campxml("msme", "Erro: "+e.toString()));
			}
			
			
			retornoxml.append(Fxml.finxml());
			response.setContentType("text/xml;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");	
			response.getWriter().write(retornoxml.toString());

		}
		
		if(Button.trim().equals("DesmarcaL")){
			exec= exec+1;
			//String retorno = "";
			StringBuffer retornoxml = new StringBuffer(Fxml.incxml());
			try{
				
				DAOt26.alterar(TbTemp26, usu_codusu, "0", null, null, Integer.parseInt(linhaid));
				
			}catch (Exception e) {
				e.printStackTrace();
				retornoxml.append(Fxml.campxml("msme", "Erro: "+e.toString()));
			}
			
			
			retornoxml.append(Fxml.finxml());
			response.setContentType("text/xml;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");	
			response.getWriter().write(retornoxml.toString());

		}
		
		if(Button.trim().equals("Fechar")){
			exec = exec + 1;	
			response.sendRedirect("principal.jsp");
		}

		if(exec == 0){
			request.setAttribute("menssagem",Button);		  		  		
			RequestDispatcher dispatcher = request.getRequestDispatcher("errorregistro.jsp");
			dispatcher.forward(request,response);				  				   
		}        
	}
	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}	

}